package cn.keepme.ep.member.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.subject.Subject;
import org.jweb.core.bean.ReplyDataMode;
import org.jweb.core.query.hibernate.qbc.CriteriaQuery;
import org.jweb.core.util.StringUtil;
import org.jweb.core.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.keepme.ep.auth.transfer.vo.authen.AuthUserVO;
import cn.keepme.ep.auth.transfer.vo.authen.UserCategoryTradeVO;
import cn.keepme.ep.common.entity.DictType;
import cn.keepme.ep.common.service.SMSServiceI;
import cn.keepme.ep.common.service.SysServiceI;
import cn.keepme.ep.member.entity.GeneralUserEntity;
import cn.keepme.ep.member.entity.UserCategoryEntity;
import cn.keepme.ep.member.entity.UserCategoryTradeEntity;
import cn.keepme.ep.member.transfer.form.member.MemberRegistForm;
import cn.keepme.ep.member.transfer.form.member.UserCategoryForm;
import cn.keepme.ep.member.transfer.form.member.UserCategorySearchForm;
import cn.keepme.ep.member.transfer.form.member.UserCategoryTradeForm;
import cn.keepme.ep.member.transfer.form.member.UserCategoryTradeSearchForm;
import cn.keepme.ep.member.transfer.vo.DictTypeVO;
import cn.keepme.ep.member.transfer.vo.UserCategoryVO;
import cn.keepme.ep.util.CommonMethod;
import cn.keepme.ep.util.MemberUtil;

@Controller
@RequestMapping("/setting")
public class SettingController extends BaseController{
	@Autowired
	private SysServiceI sysService;
	@Autowired
	private SMSServiceI smsService;
	@Autowired
	private EhCacheManager ehcacheCacheManager;
	
	@RequestMapping(value = "/tradeAdvice")
	@ResponseBody
	public ReplyDataMode order(MemberRegistForm saveForm,HttpServletRequest req){
		ReplyDataMode j = new ReplyDataMode();
		
		if(	!MemberUtil.validSMSCode(saveForm.getMphone(), saveForm.getValidCode(), ehcacheCacheManager)){
			j.setSuccess(false);
			return j;
		}
		
		GeneralUserEntity userEntity = (GeneralUserEntity)saveForm.toEntity();
		this.sysService.save(userEntity);
		
		j.setSuccess(true);
		return j;
	}
	
	
	/**
	 * 读取当前用户配置
	 * @param mphone
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/usercategory")
	@ResponseBody
	public ReplyDataMode userCategory(HttpServletRequest req){
		ReplyDataMode j = new ReplyDataMode();
		Subject currentUser = SecurityUtils.getSubject();
		AuthUserVO userInfo = (AuthUserVO)currentUser.getSession().getAttribute("userInfo");
		if(userInfo != null && StringUtil.isNotEmpty(userInfo.getId())){
			UserCategorySearchForm searchForm = new UserCategorySearchForm();
			searchForm.setUserId(userInfo.getId());
			searchForm.emptyValue2NullValue();
			CriteriaQuery cq = searchForm.getCriteriaQuery();
			List<UserCategoryEntity> userCategoryList = this.sysService.list(cq);
			
			
			
			
			List<UserCategoryVO> ulist = new ArrayList<UserCategoryVO>();
			for(UserCategoryEntity c:userCategoryList){
				UserCategoryVO vo = new UserCategoryVO();
//				vo.copyEntity(c);
				vo.setCategoryCode(c.getCategoryCode());
				vo.setCategoryId(c.getCategoryId());
				vo.setCategoryName(c.getTradeName());
				vo.setGeneralUserId(c.getGeneralUserId());
				vo.setId(c.getId());
				vo.setStatus(c.getTradeRoomIdStatus());
				
				ulist.add(vo);
			}
			j.setData(ulist);
			j.setSuccess(true);
		} else {
			j.setSuccess(false);
		}
		return j;
	}
	
	/**
	 * 喊单设置数据字典
	 * @param mphone
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/notifySettingDict")
	@ResponseBody
	public ReplyDataMode notifySettingDict(HttpServletRequest req){
		ReplyDataMode j = new ReplyDataMode();
		List<DictType> dictTypeList = this.sysService.findDict("custom");
		List<DictTypeVO> dictTypeVOList = new ArrayList<DictTypeVO>();
		for(DictType d : dictTypeList){
			DictTypeVO vo = new DictTypeVO();
			vo.copyEntity(d);
			dictTypeVOList.add(vo);
		}
		j.setSuccess(true);
		j.setData(dictTypeVOList);
		return j;
	}
	/**
	 * 修改当前用户配置
	 * @param mphone
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/saveset")
	@ResponseBody
	public ReplyDataMode saveSet(UserCategoryForm form,HttpServletRequest req){
		ReplyDataMode j = new ReplyDataMode();
		try {
			Subject currentUser = SecurityUtils.getSubject();
			AuthUserVO userInfo = (AuthUserVO)currentUser.getSession().getAttribute("userInfo");
			if(userInfo != null){
				UserCategorySearchForm searchForm = new UserCategorySearchForm();
				searchForm.setUserId(userInfo.getId());
				searchForm.setCode(form.getCode());
				CriteriaQuery cq = searchForm.getCriteriaQuery();
				List<UserCategoryEntity> userCategoryList = this.sysService.list(cq);
				if(userCategoryList.isEmpty()){
					form.emptyValue2NullValue();
					UserCategoryEntity userCategory = (UserCategoryEntity)form.toEntity();
					userCategory.setGeneralUserId(userInfo.getId());
					this.sysService.saveOrUpdate(userCategory);
				} else {
					UserCategoryEntity userCategory = userCategoryList.get(0);
//					userCategory.setStatus(form.getStatus());
					userCategory.setTradeRoomIdStatus(form.getStatus());
					this.sysService.saveOrUpdate(userCategory);
				}
				
				//更新当前会话中缓存的用户信息
				if(currentUser.isAuthenticated()){
					AuthUserVO user = (AuthUserVO)currentUser.getSession().getAttribute("userInfo");
					 List<cn.keepme.ep.auth.transfer.vo.authen.UserCategoryVO> ulist = getNotifySetingInfo(user.getId());
					user.setUlist(ulist);
					currentUser.getSession().setAttribute("userInfo", user);
				} 
				
				j.setSuccess(true);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		return j;
	}
	
	/**
	 * 修改当前 临时用户 配置
	 * @param mphone
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/saveSetTmpUser")
	@ResponseBody
	public ReplyDataMode saveSetTmpUser(UserCategoryTradeForm form,HttpServletRequest req){
		ReplyDataMode j = new ReplyDataMode();
		try {
			Subject currentUser = SecurityUtils.getSubject();
			AuthUserVO userInfo = (AuthUserVO)currentUser.getSession().getAttribute("userInfo");   // 登陆用户
			AuthUserVO userInfoTmp = (AuthUserVO)currentUser.getSession().getAttribute("userInfoTmp");  // 临时用户
			
			// 判断用户是否是登陆后的userInfo
			if(userInfo != null){
				// 代码进到这里说明用户已经登陆

				// 获取临时用户。临时用户表里有该用户缓存信息
				UserCategorySearchForm searchForm = new UserCategorySearchForm();
				searchForm.setUserId(userInfo.getId());
//				searchForm.setCategoryId(form.getCode());
//				List<DictType> dictTypeList = this.sysService.findDict("custom");
//				Map<String,DictType> dictTypeMap = new HashMap<String,DictType>();
//				DictType dictType = dictTypeMap.get(form.getCode());
//				if(dictType != null){
//				}
				String categorycode = getCode(form.getCode());
				searchForm.setCode(categorycode);
				
				CriteriaQuery cq = searchForm.getCriteriaQuery();
				List<UserCategoryEntity> userCategoryList = this.sysService.list(cq);
				if(userCategoryList.isEmpty()){

				} else {
					UserCategoryEntity userCategory = userCategoryList.get(0);
					userCategory.setTradeRoomIdStatus(form.getStatus());  // 修改交易所品种对应房间 有效状态
					this.sysService.saveOrUpdate(userCategory);
				}
				
				//更新当前会话中缓存的 临时用户信息
				AuthUserVO user = (AuthUserVO)currentUser.getSession().getAttribute("userInfo");
				List<cn.keepme.ep.auth.transfer.vo.authen.UserCategoryVO> ulist = CommonMethod.getUserInfo(this.sysService, userInfo.getId());
				user.setUlist(ulist);
				currentUser.getSession().setAttribute("userInfo", user);
				
				j.setSuccess(true);
				
			
			}
			else
			{
				if(userInfoTmp != null){
					// 获取临时用户。临时用户表里有该用户缓存信息
					UserCategoryTradeSearchForm searchForm = new UserCategoryTradeSearchForm();
					searchForm.setUserId(userInfoTmp.getId());
					searchForm.setCategoryId(form.getCode());
					CriteriaQuery cq = searchForm.getCriteriaQuery();
					List<UserCategoryTradeEntity> userCategoryList = this.sysService.list(cq);
					if(userCategoryList.isEmpty()){

					} else {
						UserCategoryTradeEntity userCategory = userCategoryList.get(0);
						userCategory.setTradeRoomIdStatus(form.getStatus());  // 修改交易所品种对应房间 有效状态
						this.sysService.saveOrUpdate(userCategory);
					}
					
					//更新当前会话中缓存的 临时用户信息
					AuthUserVO user = (AuthUserVO)currentUser.getSession().getAttribute("userInfoTmp");
					List<cn.keepme.ep.auth.transfer.vo.authen.UserCategoryTradeVO> ulist = getTmpUserInfo(userInfoTmp.getId());
					user.setTmpulist(ulist);
					currentUser.getSession().setAttribute("userInfoTmp", user);
					
					j.setSuccess(true);
					
				}else{
					// 不存在没有userInfo，并且没有userInfoTmp
					log.error("不存在没有userInfo，并且没有userInfoTmp，显示此信息说明代码有问题，有可能缓存没存上");
					/*
					UserCategoryTradeSearchForm searchForm = new UserCategoryTradeSearchForm();
					searchForm.setCategoryId(form.getCode());
					CriteriaQuery cq = searchForm.getCriteriaQuery();
					List<UserCategoryTradeEntity> userCategoryList = this.sysService.list(cq);
					if(userCategoryList.isEmpty()){

					} else {
						UserCategoryTradeEntity userCategory = userCategoryList.get(0);
						userCategory.setTradeRoomIdStatus(form.getStatus());  // 修改交易所品种对应房间 有效状态
						this.sysService.saveOrUpdate(userCategory);
					}
					
					//更新当前会话中缓存的 临时用户信息
					AuthUserVO user = (AuthUserVO)currentUser.getSession().getAttribute("userInfoTmp");
					List<com.crinser.tp.auth.transfer.vo.authen.UserCategoryTradeVO> ulist = getTmpUserInfo(userInfoTmp.getId());
					user.setTmpulist(ulist);
					currentUser.getSession().setAttribute("userInfoTmp", user);
					
					j.setSuccess(true);
					*/
					
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		return j;
	}
	
	public String getCode(String categoryId){
		String code = "";
		String sql = "select t1.category_code from tp_analyze_category t1,tp_analyze_room t2 where t1.id=t2.category_code and t1.id ='"+categoryId+ "'";
		List<String> ucList = this.sysService.findListbySql(sql);
		for (Object obj : ucList) {
			String u =  (String) obj;
			code = u;
		}
		return code;
	}
	private List<UserCategoryTradeVO> getTmpUserInfo(String userId){
		//获交易类型取数据字典
		List<DictType> tradeTypeDictTypeList = this.sysService.findDict("custom");
		Map<String,DictType> tradeTypeDictTypeMap = new HashMap<String,DictType>();
		for(DictType d : tradeTypeDictTypeList){
			tradeTypeDictTypeMap.put(d.getTypecode(), d);
		}
		
		UserCategoryTradeSearchForm searchForm = new UserCategoryTradeSearchForm();
		searchForm.setUserId(userId);
		CriteriaQuery cq = searchForm.getCriteriaQuery();
		List<UserCategoryTradeEntity> userCategoryList = this.sysService.list(cq);
		
		List<UserCategoryTradeVO> ulist = new ArrayList<UserCategoryTradeVO>();
		for(UserCategoryTradeEntity c : userCategoryList){
			UserCategoryTradeVO vo = new UserCategoryTradeVO();
			vo.setStatus(c.getTradeRoomIdStatus());
			vo.setCode(c.getCategoryCode());
			vo.setRoomid(c.getTradeRoomId());
			String code = c.getCategoryCode();
			if(StringUtil.isNotEmpty(code)){
				DictType temp = tradeTypeDictTypeMap.get(code);
				if(temp != null){
					vo.setName(temp.getTypename());
				}
			}
			ulist.add(vo);
		}
		
		return ulist;
		
	}
	
	
	
	private List<cn.keepme.ep.auth.transfer.vo.authen.UserCategoryVO> getNotifySetingInfo(String userId){
		//获交易类型取数据字典
		List<DictType> tradeTypeDictTypeList = this.sysService.findDict("custom");
		Map<String,DictType> tradeTypeDictTypeMap = new HashMap<String,DictType>();
		for(DictType d : tradeTypeDictTypeList){
			tradeTypeDictTypeMap.put(d.getTypecode(), d);
		}
		
		UserCategorySearchForm searchForm = new UserCategorySearchForm();
		searchForm.setUserId(userId);
		CriteriaQuery cq = searchForm.getCriteriaQuery();
		List<UserCategoryEntity> userCategoryList = this.sysService.list(cq);
		
		List<cn.keepme.ep.auth.transfer.vo.authen.UserCategoryVO> ulist = new ArrayList<cn.keepme.ep.auth.transfer.vo.authen.UserCategoryVO>();
		for(UserCategoryEntity c : userCategoryList){
			cn.keepme.ep.auth.transfer.vo.authen.UserCategoryVO vo = new cn.keepme.ep.auth.transfer.vo.authen.UserCategoryVO();
//			vo.setStatus(c.getStatus());
			vo.setStatus(c.getTradeRoomIdStatus());
			vo.setCode(c.getCategoryCode());
			String code = c.getCategoryCode();
			if(StringUtil.isNotEmpty(code)){
				DictType temp = tradeTypeDictTypeMap.get(code);
				if(temp != null){
					vo.setName(temp.getTypename());
				}
			}
			ulist.add(vo);
		}
		
		return ulist;
		
//		List<com.crinser.tp.auth.transfer.vo.authen.UserCategoryVO> ulist = new ArrayList<com.crinser.tp.auth.transfer.vo.authen.UserCategoryVO>();
//		try {
//			String sql = "select  t1.category_name,t1.category_code,t1.category_name,t2.general_user_id ,t2.category_id,t2.status,t2.id from tp_user_category t2   LEFT JOIN tp_analyze_category t1  on t2.category_id = t1.id where 1 = 1 and t2.general_user_id = '" + mphone + "'";
//			List<Map<String,Object>> list  = sysService.findForJdbc(sql, null);
//			com.crinser.tp.auth.transfer.vo.authen.UserCategoryVO vo = new com.crinser.tp.auth.transfer.vo.authen.UserCategoryVO();
//			
//			for(Map<String,Object> l:list){
//				vo = new com.crinser.tp.auth.transfer.vo.authen.UserCategoryVO();
//				vo.setStatus(l.get("status").toString());
//				vo.setCode(l.get("category_code").toString());
//				vo.setName(l.get("category_name").toString());
//				ulist.add(vo);
//			}
//			
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return ulist;
	}
}
